/**
 * 
 */
package com.jushu.storbox.service;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.CopyFileRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.CopyFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderSearchRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.MoveFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.Order;
import com.huawei.sharedrive.sdk.android.modelV2.request.SharedUserV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.serviceV2.FileClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.FolderClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.ShareClientV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class RemoteShareFileService extends AbstractBaseService implements
		IRemoteShareFileService {

	private final static String TAG = "RemoteShareFileService";
	private boolean isChanged = false;

	/**
	 * 
	 */
	public RemoteShareFileService() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public FileInfoResponseV2 getFileResponse(String fileId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public FileInfoResponseV2 renameFile(String ownerId, String fileId, String name)
			throws ClientException {
        shareDriveApplication.smartAuthorization();
		return FileClientV2.getInstance().renameFile(ownerId, fileId,
				this.getAuthCode(), name);
	}

	@Override
	public String deleteFile(String ownerId, String fileID) throws ClientException {
		FileClientV2 fileClient = FileClientV2.getInstance();
        shareDriveApplication.smartAuthorization();
		String response = fileClient.deleteFile(ownerId, fileID,
				this.getAuthCode());
		return response;
	}

	@Override
	public String moveFile(String ownerId, String fileId, MoveFileRequestV2 request)
			throws ClientException {
        shareDriveApplication.smartAuthorization();
		return FileClientV2.getInstance().moveFile(ownerId, fileId,
				request, this.getAuthCode());
	}

	@Override
	public String copyFolder(String folderID, CopyFileRequest request)
			throws ClientException {
		return null;
	}

	@Override
	public List<FileFolderInfo> searchRemote(Context context, int limit,
			int offset, String name) throws ClientException {	
		FolderSearchRequestV2 request = new FolderSearchRequestV2();
		// request.setLimit(limit);
		request.setName(name);
		// request.setOffset(offset);
		request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());
        shareDriveApplication.smartAuthorization();
		FolderListResponseV2 response = FolderClientV2.getInstance()
				.search(request,ShareDriveApplication.getInstance().getAuthorization());
		
		List<FileFolderInfo> folderList = FileHelper
				.convertFolderRemoteToLocal(response);
		List<FileFolderInfo> fileList = FileHelper
				.convertFileRemoteToLocal(response);
		folderList.addAll(fileList);
		return folderList;
	}

	@Override
	public List<FileFolderInfo> getFileFolderList(String ownerId, boolean autoManualFlag,
			Context context, String folderID, String des, int limit,
			int offset, String orderby) throws ClientException {
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		List<FolderInfo> folderInfoList = null;
		List<FileInfo> fileInfoList = null;
		long lastRefreshTime = DAOFactory.instance(context).getFolderDao()
				.getLastRefreshTime(ownerId, folderID);
		long nowTime = System.currentTimeMillis();
		SharedPreferences settings = context.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE,
				false);
		if (isOnline
				&& (!autoManualFlag || (1 * 60 * 1000 < nowTime
						- lastRefreshTime))) {
			LogUtil.i(TAG, "Get server file&folder list...");
			
			FolderListRequestV2 request = new FolderListRequestV2();
			request.setFolderID(folderID);
			request.setLimit(limit);
			request.setOffset(offset);
			request.setOwnerID(ownerId);

			Order o = new Order();
			o.setDirection(des);
			o.setField(orderby);
			List<Order> olist = new ArrayList<Order>();
			olist.add(o);
			request.setOrder(olist);

	        shareDriveApplication.smartAuthorization();
			final FolderListResponseV2 response = FolderClientV2.getInstance()
					.getFolderInfoList(request, this.getAuthCode());
			
			List<FileFolderInfo> folderList = FileHelper
					.convertFolderRemoteToLocal(response);
			List<FileFolderInfo> fileList = FileHelper
					.convertFileRemoteToLocal(response);
			fileFolderInfoList.addAll(folderList);
			fileFolderInfoList.addAll(fileList);
			folderInfoList = DAOFactory.instance(context).getFolderDao()
					.getFolderList(ownerId, folderID);
			FolderInfo parentFolder = DAOFactory.instance(context)
					.getFolderDao().getFolderById(ownerId, folderID);
			fileInfoList = DAOFactory.instance(context).getFileDao()
					.getFileList(ownerId, folderID);
			FileHelper.compareServiceClientFolder(context,
					response.getFolders(), folderInfoList, ownerId, folderID);
			FileHelper.compareServiceClientFile(context, response.getFiles(),
					fileInfoList, ownerId, folderID);
			DAOFactory.instance(context).getFolderDao()
					.updateLastRefreshTime(ownerId, folderID, nowTime);
		}
		fileFolderInfoList.clear();
		folderInfoList = DAOFactory.instance(context).getFolderDao()
				.getFolderList(ownerId, folderID);
		fileFolderInfoList.addAll(folderInfoList);
		fileInfoList = DAOFactory.instance(context).getFileDao()
				.getFileList(ownerId, folderID);
		fileFolderInfoList.addAll(fileInfoList);

		return fileFolderInfoList;
	}

	@Override
	public List<FileFolderInfo> getFileFolderList(Context context,
			String ownerId, String folderID) {
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		List<FolderInfo> folderInfoList = null;
		List<FileInfo> fileInfoList = null;
		folderInfoList = DAOFactory.instance(context).getFolderDao()
				.getFolderList(ownerId, folderID);
		fileFolderInfoList.addAll(folderInfoList);
		fileInfoList = DAOFactory.instance(context).getFileDao()
				.getFileList(ownerId, folderID);
		fileFolderInfoList.addAll(fileInfoList);

		return fileFolderInfoList;
	}

	@Override
	public List<FileFolderInfo> getSharedFileFolderList(boolean autoManualFlag,
			Context context, String folderID, String des, int limit,
			int offset, String orderby, String shareOwnerId, String ownerBy) {
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		List<FolderInfo> folderInfoList = null;
		List<FileInfo> fileInfoList = null;

		long lastRefreshTime = DAOFactory.instance(context).getShareFolderDao()
				.getLastRefreshTime(shareOwnerId, folderID);
		long nowTime = System.currentTimeMillis();
		SharedPreferences settings = context.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE,
				false);
		if (isOnline
				&& (!autoManualFlag || (1 * 60 * 1000 < nowTime
						- lastRefreshTime))) {
			LogUtil.i(TAG, "Get server file&folder list...");
			
			FolderListRequestV2 request = new FolderListRequestV2();
			request.setFolderID(folderID);
			request.setLimit(limit);
			request.setOffset(offset);
			request.setOwnerID(shareOwnerId);

			Order o = new Order();
			o.setDirection(des);
			o.setField(orderby);
			List<Order> olist = new ArrayList<Order>();
			olist.add(o);
			request.setOrder(olist);

			FolderListResponseV2 response;
			try {
		        shareDriveApplication.smartAuthorization();
				response = FolderClientV2.getInstance().getFolderInfoList(
						request, this.getAuthCode());
				List<FileFolderInfo> folderList = FileHelper
						.convertFolderRemoteToLocal(response);
				List<FileFolderInfo> fileList = FileHelper
						.convertFileRemoteToLocal(response);
				fileFolderInfoList.addAll(folderList);
				fileFolderInfoList.addAll(fileList);
				folderInfoList = DAOFactory.instance(context)
						.getShareFolderDao().getFolderList(folderID, ownerBy);
				fileInfoList = DAOFactory.instance(context).getShareFileDao()
						.getFileList(folderID, ownerBy);
				FileHelper.compareShareServiceClientFolder(context,
						response.getFolders(), folderInfoList, folderID);
				FileHelper.compareShareServiceClientFile(context,
						response.getFiles(), fileInfoList);
				DAOFactory.instance(context).getFolderDao()
						.updateLastRefreshTime(shareOwnerId, folderID, nowTime);
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				LogUtil.e(TAG, "getSharedFileFolderList exception: StatusCode:"
						+ e.getStatusCode() + " | code:" + e.getCode()
						+ " | message:" + e.getLocalizedMessage());
				fileFolderInfoList.clear();
				folderInfoList = DAOFactory.instance(context)
						.getShareFolderDao().getFolderList(folderID, ownerBy);
				fileFolderInfoList.addAll(folderInfoList);
				fileInfoList = DAOFactory.instance(context).getShareFileDao()
						.getFileList(folderID, ownerBy);
				fileFolderInfoList.addAll(fileInfoList);
				return fileFolderInfoList;
			}
		}
		fileFolderInfoList.clear();
		folderInfoList = DAOFactory.instance(context).getShareFolderDao()
				.getFolderList(folderID, ownerBy);
		fileFolderInfoList.addAll(folderInfoList);
		fileInfoList = DAOFactory.instance(context).getShareFileDao()
				.getFileList(folderID, ownerBy);
		fileFolderInfoList.addAll(fileInfoList);

		return fileFolderInfoList;
	}

	@Override
	public synchronized List<FileFolderInfo> getSharedFileFolderListPage(
			boolean autoManualFlag, final Context context, String folderID,
			String des, String orderby, Handler handler, String shareOwnerId) {
		LogUtil.i(TAG, "getSharedFileFolderListPage...");
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		// List<FolderInfo> folderInfoList = null;
		// List<FileInfo> fileInfoList = null;
		long lastRefreshTime = DAOFactory.instance(context).getShareFolderDao()
				.getLastRefreshTime(shareOwnerId, folderID);
		long nowTime = System.currentTimeMillis();
		SharedPreferences settings = context.getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		// boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE,
		// false);
		if (ShareDriveApplication.getInstance()
				.getWifiController().getNetworkState()
				&& (!autoManualFlag || (ClientConfig.REFRESH_TIME < nowTime
						- lastRefreshTime))) {
			LogUtil.i(TAG, "Get server file&folder list...");
			fileFolderInfoList = getServerFileFolderListPage(context, folderID,
					des, orderby, fileFolderInfoList, nowTime, handler,
					shareOwnerId);
			if (null != fileFolderInfoList && 0 != fileFolderInfoList.size()) {
				LogUtil.i(TAG, "get server list:" + fileFolderInfoList.size());
				return fileFolderInfoList;
			}
		}
		fileFolderInfoList.clear();
		List<FolderInfo> folderInfoList = DAOFactory
				.instance(context)
				.getShareFolderDao()
				.getFolderListPage(Constant.SHARED_GET_FILE_LIST_STATE,
						folderID);
		fileFolderInfoList.addAll(folderInfoList);
		List<FileInfo> fileInfoList = DAOFactory.instance(context)
				.getShareFileDao()
				.getFileListPage(Constant.SHARED_GET_FILE_LIST_STATE, folderID);
		fileFolderInfoList.addAll(fileInfoList);
		/*
		 * //test if (null != fileFolderInfoList && 0 !=
		 * fileFolderInfoList.size()) { Log.i("~~~", "get local list:" +
		 * fileFolderInfoList.size()); } else { Log.e("~~~", "get local list:" +
		 * fileFolderInfoList.size()); } //test if (null == fileFolderInfoList
		 * || 0 == fileFolderInfoList.size()) { fileFolderInfoList =
		 * getServerFileFolderListPage(context, folderID, des, orderby,
		 * fileFolderInfoList, nowTime, handler,shareOwnerId); } //test if (null
		 * != fileFolderInfoList && 0 != fileFolderInfoList.size()) {
		 * Log.v("~~~", "local is null get server list:" +
		 * fileFolderInfoList.size()); } else { Log.e("~~~",
		 * "local is null get server list:" + fileFolderInfoList.size()); }
		 * //test
		 */
		return fileFolderInfoList;
	}

	@Override
	public List<FileFolderInfo> getServerShareResourceList(Context context,
			String des, String folderId, String shareOwnerId, String orderBy)
			throws ClientException {
		boolean isFolderChange = false;
		boolean isFileChange = false;
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		long nowTime = System.currentTimeMillis();
		final FolderListRequestV2 request = new FolderListRequestV2();		
		request.setFolderID(folderId);
		request.setLimit(1000);
		request.setOffset(0);
		request.setOwnerID(shareOwnerId);

		Order o = new Order();
		o.setDirection(des);
		o.setField(orderBy);
		List<Order> olist = new ArrayList<Order>();
		olist.add(o);
		request.setOrder(olist);

        shareDriveApplication.smartAuthorization();
		FolderListResponseV2 response = FolderClientV2.getInstance()
				.getFolderInfoList(request, this.getAuthCode());
		
		List<FolderInfo> folderInfoList = DAOFactory.instance(context)
				.getShareFolderDao().getFolderList(folderId, shareOwnerId);
		List<FileInfo> fileInfoList = DAOFactory.instance(context)
				.getShareFileDao().getFileList(folderId, shareOwnerId);

		isFolderChange = FileHelper.compareShareServiceClientFolder(context,
				response.getFolders(), folderInfoList, folderId);
		isFileChange = FileHelper.compareShareServiceClientFile(context,
				response.getFiles(), fileInfoList);
		setShareResourceIsChanged(isFolderChange, isFileChange);
		DAOFactory.instance(context).getShareFolderDao()
				.updateLastRefreshTime(shareOwnerId, folderId, nowTime);
		List<FolderInfo> folderList = DAOFactory.instance(context)
				.getShareFolderDao().getFolderList(folderId, shareOwnerId);
		List<FileInfo> fileList = DAOFactory.instance(context)
				.getShareFileDao().getFileList(folderId, shareOwnerId);
		fileFolderInfoList.addAll(folderList);
		fileFolderInfoList.addAll(fileList);
		return fileFolderInfoList;
	}

	@Override
	public void setShareResourceIsChanged(boolean isFolderChange,
			boolean isFileChange) {
		// TODO Auto-generated method stub
		this.isChanged = false;
		LogUtil.i(TAG, "setShareResourceIsChanged:"+isFolderChange);
		this.isChanged = (isFolderChange || isFileChange);
	}

	@Override
	public boolean getShareResourceIsChanged() {
		return this.isChanged;
	}

	@Override
	public List<FileFolderInfo> getBaseServerShareResourceList()
			throws ClientException {
		return null;
	}

	private synchronized List<FileFolderInfo> getServerFileFolderListPage(
			final Context context, final String folderID, final String des,
			final String orderby, List<FileFolderInfo> fileFolderInfoList,
			long nowTime, Handler handler, final String shareOwnerId) {
		try {
			LogUtil.i(TAG, "getServerFileFolderListPage SHARED_COUNT_PER_PAGE:"
					+ ShareDriveApplication.getInstance().getMySharePage());
					
			final FolderListRequestV2 request = new FolderListRequestV2();
			request.setFolderID(folderID);
			request.setLimit(ClientConfig.SHARED_COUNT_PER_PAGE);
			request.setOffset(ShareDriveApplication.getInstance()
					.getMySharePage() * ClientConfig.SHARED_COUNT_PER_PAGE);
			request.setOwnerID(shareOwnerId);

			Order o = new Order();
			o.setDirection(des);
			o.setField(orderby);
			List<Order> olist = new ArrayList<Order>();
			olist.add(o);
			request.setOrder(olist);

	        shareDriveApplication.smartAuthorization();
			final FolderListResponseV2 response = FolderClientV2.getInstance()
					.getFolderInfoList(request, this.getAuthCode());

			List<FileFolderInfo> folderList = FileHelper
					.convertFolderRemoteToLocal(response);
			List<FileFolderInfo> fileList = FileHelper
					.convertFileRemoteToLocal(response);
			fileFolderInfoList.addAll(folderList);
			fileFolderInfoList.addAll(fileList);
			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					// List<FolderInfo> folderInfoList =
					// DAOFactory.instance(context).getFolderDao().getFolderListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE,
					// folderID);
					// FolderInfo parentFolder =
					// DAOFactory.instance(context).getFolderDao().getFolderById(folderID);
					// List<FileInfo> fileInfoList =
					// DAOFactory.instance(context).getFileDao().getFileListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE,
					// folderID);
					try {
						request.setLimit(1000);
						request.setOffset(0);
				        shareDriveApplication.smartAuthorization();
						FolderListResponseV2 responseAll = FolderClientV2
								.getInstance().getFolderInfoList(
										request,
										RemoteShareFileService.this
												.getAuthCode());
						LogUtil.i(TAG, "server list file:"
								+ responseAll.getFiles().size() + " | folder:"
								+ responseAll.getFolders().size());
						List<FolderInfo> folderInfoList = DAOFactory
								.instance(context).getShareFolderDao()
								.getFolderList(folderID, shareOwnerId);
						List<FileInfo> fileInfoList = DAOFactory
								.instance(context).getShareFileDao()
								.getFileList(folderID, shareOwnerId);
						// List<FileInfo> fileInfoList = DAOFactory
						// .instance(context).getFileDao()
						// .getFileList(folderID);
						FileHelper.compareShareServiceClientFolder(context,
								responseAll.getFolders(), folderInfoList,
								folderID);
						FileHelper.compareShareServiceClientFile(context,
								responseAll.getFiles(), fileInfoList);
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}
			}).start();
			DAOFactory.instance(context).getShareFolderDao()
					.updateLastRefreshTime(shareOwnerId, folderID, nowTime);
		} catch (ClientException e) {
			// TODO: handle exception
			LogUtil.e(
					TAG,
					"getSharedFileFolderList exception: StatusCode:"
							+ e.getStatusCode() + " | code:" + e.getCode()
							+ " | message:" + e.getLocalizedMessage());
			Message msg = new Message();
			msg.what = ClientConfig.FAILTOOBTAINLIST;
			msg.obj = e.getStatusCode();
			handler.sendMessage(msg);
			e.printStackTrace();
		}

		return fileFolderInfoList;
	}

	@Override
	public FileInfoResponseV2 copyFileToTarget(FileFolderInfo copyedFileFolderInfo, 
			FileFolderInfo targetFolder) throws ClientException {
		
		String fileID = copyedFileFolderInfo.getiNodeId();
		if (StringUtil.isBlank(fileID)) {
			fileID = copyedFileFolderInfo.getId();
		}
		
		CopyFileRequestV2 request = new CopyFileRequestV2();
		request.setAutoRename(true);
		request.setDestOwnerId(Long.valueOf(ShareDriveApplication.getInstance().getWnerID()));
		request.setDestParent(Long.valueOf(targetFolder.getId()));
		request.setLink(null);
		
        shareDriveApplication.smartAuthorization();
		return FileClientV2.getInstance().copyFile(copyedFileFolderInfo.getOwnerBy(), fileID, 
				ShareDriveApplication.getInstance().getAuthorization(), request);
	}

	@Override
	public void rejectShare(String authorization, long ownerId, long iNodeId) throws ClientException {
		// TODO Auto-generated method stub
		SharedUserV2 sharedUser =new SharedUserV2();
		sharedUser.setId(ShareDriveApplication.getInstance().getWnerID());
        shareDriveApplication.smartAuthorization();
		ShareClientV2.getInstance().deleteShareShips(authorization, sharedUser, String.valueOf(ownerId), String.valueOf(iNodeId));
	}
	
	
}
